package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;

import dbhelper.Users;

import utils.UsersHelper;
import entities.User;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String USERNAME = "userName";
	private static final String LOGINRESULT = "loginResult";
	public static final String LOGGED_USER_ID = "loggedUserID";
	private static final String PASSWORD = "password";
	private static final String DISPLAY_NAME = "displayName";
       
   
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }


	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String displayName = getUserDisplayName(request);
		boolean result = false;
		response.setContentType("text/json");
		if(displayName != null){
			result = true; // user already logged in
		}else{
		User user = getUser(request),dbUser;
		if((dbUser = UsersHelper.login(user)) != null){
		session.setAttribute(LOGGED_USER_ID, dbUser.getID());
		displayName = dbUser.getDisplayName();
		result = true;
		}
		}
		try {
			response.getWriter().write(
					new JSONObject().put(LOGINRESULT, result).
					put(DISPLAY_NAME, displayName).toString()
					);
		} catch (JSONException e) {
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}	
}
	
	
	private static User getUser(HttpServletRequest request){
		JSONObject jsonObject ;
		String str = null;
		
		try {
			str = request.getReader().readLine();
			jsonObject = new JSONObject(str);
			return new User(
					jsonObject.optString(USERNAME),
					jsonObject.optString(PASSWORD));
			
		}catch (JSONException | IOException e){
			e.printStackTrace();
		}
		return null;
	}
	
	public static String getUserDisplayName(HttpServletRequest request){
		long userID = ServletsUtil.getUserID(request);
		User user;
		if(userID > -1 && (user = Users.getUserByID(userID)) != null){
			return user.getDisplayName();
		}
		return null;
	}
	
}
